package com.wwwarehouse.usercenter.fragment.permissiondistribute;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.time_pick.DateAndTimePickerDialog;
import com.wwwarehouse.common.custom_widget.time_pick.DateUtil;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.usercenter.R;
import com.wwwarehouse.usercenter.bean.authoritydistribute.AuthProcessUkidBean;
import com.wwwarehouse.usercenter.bean.authoritydistribute.AuthorityDistributeItemBean;
import com.wwwarehouse.usercenter.bean.authoritydistribute.DistributeResultBean;
import com.wwwarehouse.usercenter.bean.authoritydistribute.PowerDistributeBean;
import com.wwwarehouse.usercenter.constant.UserCenterConstant;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author : mundane
 * @time : 2017/9/21 17:12
 * @description :
 * @file : AuthoritySetTimeFragment.java
 */

public class AuthoritySetTimeFragment extends BaseFragment {

    private View                                   mLlStartTime;
    private TextView                               mTvStartTime;
    private TextView                               mTvEndTime;
    private View                                   mLlEndTime;
    private Date                                   mStartDate;
    private Date                                   mEndDate;
    private View                                   mBtnDefaultStart;
    private View                                   mBtnDefaultEnd;
    private ArrayList<AuthorityDistributeItemBean> mDataList;
    private String                                 mStartTime;
    private String                                 mEndTime;
    private Date                                   mDefaultStartDate;
    private Date                                   mDefaultEndDate;
    private View                                   mBtnToDistribute;
    private String                                 mBusinessUnitId;
    private ArrayList<AuthorityDistributeItemBean> mSelectedDataList;
    private NoHttpUtils.OnResponseListener mResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            try {
                switch (what) {
                    case 0:
                        if (TextUtils.equals("0", commonClass.getCode())) {
                            AuthProcessUkidBean authProcessUkidBean = JSON.parseObject(commonClass.getData().toString(), AuthProcessUkidBean.class);
                            popFragment();
                            pushFragment(AuthorityDistributeQRcodeFragment.newInstance(authProcessUkidBean, mBusinessUnitId, mSelectedDataList));
                        } else if (TextUtils.equals("200201", commonClass.getCode())) {
                            PermissionNotFoundFragment fragment = new PermissionNotFoundFragment();
                            Bundle bundle = new Bundle();
                            bundle.putInt(PermissionNotFoundFragment.KEY_TYPE, 0);
                            fragment.setArguments(bundle);
                            popFragment();
                            pushFragment(fragment);
                        } else if (TextUtils.equals("210018", commonClass.getCode())) {
                            PermissionNotFoundFragment fragment = new PermissionNotFoundFragment();
                            Bundle bundle = new Bundle();
                            bundle.putInt(PermissionNotFoundFragment.KEY_TYPE, 1);
                            fragment.setArguments(bundle);
                            popFragment();
                            pushFragment(fragment);
                        } else {
                            ToastUtils.showToast(commonClass.getMsg());
                        }
                        break;
                    case 1:
                        if ("0".equals(commonClass.getCode())) {
                            PowerDistributeBean powerDistributeBean = JSON.parseObject(commonClass.getData().toString(), PowerDistributeBean.class);
                            int status = powerDistributeBean.getStatus();
                            //（0成功， 1失败， 2 部分成功， 3 异常）
                            switch (status) {
                                case 0:
                                    PermissionDistributeSuccessFragment fragment = new PermissionDistributeSuccessFragment();
                                    Bundle bundle = new Bundle();
                                    DistributeResultBean bean = new DistributeResultBean();
                                    bean.setProcessId(powerDistributeBean.getProcessId());
                                    DistributeResultBean.DetailBean detailBean = new DistributeResultBean.DetailBean();
                                    detailBean.setAuthorityCount(powerDistributeBean.getDetail().getAuthorityCount());
                                    detailBean.setSelectedUserCount(powerDistributeBean.getDetail().getSelectedUserCount());
                                    bean.setDetail(detailBean);
                                    bean.setDescription(powerDistributeBean.getDescription());
                                    bean.setStatus(powerDistributeBean.getStatus());
                                    bundle.putParcelable("resultBean", bean);
                                    bundle.putString("type", "CheckDownClassFragment");
//                                    bundle.putString("personName", mPersonName);
//                                    bundle.putString("userId", mUserId);
                                    bundle.putString("buId", mBusinessUnitId);
                                    fragment.setArguments(bundle);
                                    pushFragment(fragment);
                                    break;
                                case 1:
                                    PermissionDistributeAllErrorFragment fragment1 = new PermissionDistributeAllErrorFragment();
                                    Bundle bundle1 = new Bundle();
                                    DistributeResultBean bean1 = new DistributeResultBean();
                                    bean1.setProcessId(powerDistributeBean.getProcessId());
                                    DistributeResultBean.DetailBean detailBean1 = new DistributeResultBean.DetailBean();
                                    detailBean1.setAuthorityCount(powerDistributeBean.getDetail().getAuthorityCount());
                                    detailBean1.setSelectedUserCount(powerDistributeBean.getDetail().getSelectedUserCount());
                                    bean1.setDetail(detailBean1);
                                    bean1.setDescription(powerDistributeBean.getDescription());
                                    bean1.setStatus(powerDistributeBean.getStatus());
                                    bundle1.putParcelable("resultBean", bean1);
                                    bundle1.putString("type", "CheckDownClassFragment");
//                                    bundle1.putString("personName", mPersonName);
//                                    bundle1.putString("userId", mUserId);
                                    bundle1.putString("buId", mBusinessUnitId);
                                    fragment1.setArguments(bundle1);
                                    pushFragment(fragment1);

                                    break;
                                case 2:
                                    PermissionDistributeAnySuccessFragment fragment2 = new PermissionDistributeAnySuccessFragment();
                                    Bundle bundle2 = new Bundle();
                                    DistributeResultBean bean2 = new DistributeResultBean();
                                    bean2.setProcessId(powerDistributeBean.getProcessId());
                                    DistributeResultBean.DetailBean detailBean2 = new DistributeResultBean.DetailBean();
                                    detailBean2.setAuthorityCount(powerDistributeBean.getDetail().getAuthorityCount());
                                    detailBean2.setSelectedUserCount(powerDistributeBean.getDetail().getSelectedUserCount());
                                    bean2.setDetail(detailBean2);
                                    bean2.setDescription(powerDistributeBean.getDescription());
                                    bean2.setStatus(powerDistributeBean.getStatus());
                                    bundle2.putParcelable("resultBean", bean2);
                                    bundle2.putString("type", "CheckDownClassFragment");
//                                    bundle2.putString("personName", mPersonName);
//                                    bundle2.putString("userId", mUserId);
                                    bundle2.putString("buId", mBusinessUnitId);
                                    fragment2.setArguments(bundle2);
                                    pushFragment(fragment2);

                                    break;
                                case 3:
                                    PermissionAddressNotFoundFragment fragment3 = new PermissionAddressNotFoundFragment();
                                    Bundle bundle3 = new Bundle();
                                    if (powerDistributeBean.getCardNames().size() == 0) {
                                        bundle3.putString("content", mActivity.getResources().getString(R.string.permission_description_txt));
                                    } else if (powerDistributeBean.getCardNames().size() == 1) {
                                        bundle3.putString("content", powerDistributeBean.getCardNames().get(0) + mActivity.getResources().getString(R.string.permission_description_txt));
                                    } else if (powerDistributeBean.getCardNames().size() > 1) {
                                        bundle3.putString("content", powerDistributeBean.getCardNames().get(0) + mActivity.getResources().getString(R.string.user_pr_etc) + mActivity.getResources().getString(R.string.permission_description_txt));
                                    }
                                    bundle3.putString("type", "CheckDownClassFragment");
//                                    bundle3.putString("personName", mPersonName);
//                                    bundle3.putString("userId", mUserId);
                                    bundle3.putString("buId", mBusinessUnitId);
                                    fragment3.setArguments(bundle3);
                                    pushFragment(fragment3);

                                    break;
                            }
                        }
                        break;
                    default:
                        break;
                }
            } catch (Exception e) {
                LogUtils.showLog(e.toString());
            }

        }

        @Override
        public void onFailed(String s, int i) {

        }

        @Override
        public void onFinish(int i) {
            dismissProgressDialog();
        }
    };
    private ArrayList<String> mSelectedUserIds;

    public static AuthoritySetTimeFragment newInstance(String startTime, String endTime, String businessUnitId, ArrayList<AuthorityDistributeItemBean> selectedDataList) {
        AuthoritySetTimeFragment fragment = new AuthoritySetTimeFragment();
        Bundle bundle = new Bundle();
        bundle.putString(UserCenterConstant.KEY_START_TIME, startTime);
        bundle.putString(UserCenterConstant.KEY_END_TIME, endTime);
        bundle.putString(UserCenterConstant.KEY_BUSINESS_UNIT_ID, businessUnitId);
        bundle.putParcelableArrayList(UserCenterConstant.KEY_AUTHORITY_ITEM_BEAN, selectedDataList);
        fragment.setArguments(bundle);
        return fragment;
    }

    public static AuthoritySetTimeFragment newInstance(String startTime, String endTime, String businessUnitId, ArrayList<AuthorityDistributeItemBean> selectedDataList, ArrayList userIdList) {
        AuthoritySetTimeFragment fragment = new AuthoritySetTimeFragment();
        Bundle bundle = new Bundle();
        bundle.putString(UserCenterConstant.KEY_START_TIME, startTime);
        bundle.putString(UserCenterConstant.KEY_END_TIME, endTime);
        bundle.putString(UserCenterConstant.KEY_BUSINESS_UNIT_ID, businessUnitId);
        bundle.putParcelableArrayList(UserCenterConstant.KEY_AUTHORITY_ITEM_BEAN, selectedDataList);
        bundle.putStringArrayList("selectedUserIds", userIdList);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mStartTime = bundle.getString(UserCenterConstant.KEY_START_TIME);
            mDefaultStartDate = DateUtil.formatDateStr(mStartTime, "yyyy-MM-dd HH:mm:ss");
            mEndTime = bundle.getString(UserCenterConstant.KEY_END_TIME);
            mDefaultEndDate = DateUtil.formatDateStr(mEndTime, "yyyy-MM-dd HH:mm:ss");
            mBusinessUnitId = bundle.getString(UserCenterConstant.KEY_BUSINESS_UNIT_ID);
            mSelectedDataList = bundle.getParcelableArrayList(UserCenterConstant.KEY_AUTHORITY_ITEM_BEAN);
            if (bundle.getStringArrayList("selectedUserIds") != null) {
                mSelectedUserIds = bundle.getStringArrayList("selectedUserIds");
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_settime_authority, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        // findViewById
        mLlStartTime = $(R.id.ll_start_time);
        mLlEndTime = $(R.id.ll_end_time);
        mTvStartTime = $(R.id.tv_start_time);
        mBtnToDistribute = $(R.id.btn_to_distribute);
        mTvEndTime = $(R.id.tv_end_time);
        mBtnDefaultStart = $(R.id.btn_default_start);
        mBtnDefaultEnd = $(R.id.btn_default_end);
        mLlStartTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar calendar = Calendar.getInstance();
                final Date currentDate = new Date();
                calendar.setTime(currentDate);
                int minYear = calendar.get(Calendar.YEAR);
                int minMonth = calendar.get(Calendar.MONTH) + 1;
                int minDay = calendar.get(Calendar.DAY_OF_MONTH);
                Date maxDate;
                if (mEndDate != null) {
                    if (mEndDate.before(mDefaultEndDate)) {
                        maxDate = mEndDate;
                    } else {
                        maxDate = mDefaultEndDate;
                    }
                } else {
                    maxDate = mDefaultEndDate;
                }
                calendar.setTime(maxDate);
                int maxYear = calendar.get(Calendar.YEAR);
                int maxMonth = calendar.get(Calendar.MONTH) + 1;
                int maxDay = calendar.get(Calendar.DAY_OF_MONTH);

                DateAndTimePickerDialog.Builder builder = new DateAndTimePickerDialog
                        .Builder(mActivity)
                        .setTitle("选择开始时间")
                        .setMinYear(minYear)
                        .setMinMonth(minMonth)
                        .setMinDay(minDay)
                        .setMaxYear(maxYear)
                        .setMaxMonth(maxMonth)
                        .setMaxDay(maxDay)
                        .setOnDateSelectedListener(new DateAndTimePickerDialog.OnDateTimeSelectedListener() {
                            @Override
                            public void onDateTimeSelected(String s) {
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                                String currentDateString = sdf.format(currentDate);
                                Date currentDate = DateUtil.formatDateStr(currentDateString, "yyyy-MM-dd HH:mm");
                                Date selectDate = DateUtil.formatDateStr(s, "yyyy-MM-dd HH:mm");
                                if (selectDate.before(currentDate)) {
                                    Toast.makeText(getContext(), "开始时间不能早于当前时间", Toast.LENGTH_SHORT).show();
                                } else if (selectDate.after(mDefaultEndDate)) { // 开始时间不能晚于操作者权限开始时间
                                    Toast.makeText(getContext(), "开始时间不能晚于操作者权限结束时间", Toast.LENGTH_SHORT).show();
                                } else {
                                    if (mEndDate != null) {
                                        if (!selectDate.before(mEndDate)) {
                                            Toast.makeText(mActivity, "开始时间必须早于结束时间", Toast.LENGTH_SHORT).show();
                                        } else {
                                            mStartDate = selectDate;
                                            mTvStartTime.setText(s);
                                            mBtnDefaultStart.setVisibility(View.VISIBLE);
                                        }
                                    } else {
                                        mStartDate = selectDate;
                                        mTvStartTime.setText(s);
                                        mBtnDefaultStart.setVisibility(View.VISIBLE);
                                    }
                                }
                            }

                            @Override
                            public void onCancel() {

                            }
                        });
                if (mStartDate != null) {
                    calendar.setTime(mStartDate);
                    builder.setSelectYear(calendar.get(Calendar.YEAR));
                    builder.setSelectMonth(calendar.get(Calendar.MONTH) + 1);
                    builder.setSelectDay(calendar.get(Calendar.DAY_OF_MONTH));
                    builder.setSelectHour(calendar.get(Calendar.HOUR_OF_DAY));
                    builder.setSelectMin(calendar.get(Calendar.MINUTE));
                }
                DateAndTimePickerDialog timePickerDialog = builder.create();
                timePickerDialog.show();
            }
        });
        mLlEndTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar calendar = Calendar.getInstance();
                final Date currentDate = new Date();
                Date minDate;
                if (mStartDate != null) {
                    if (mStartDate.after(currentDate)) {
                        minDate = mStartDate;
                    } else {
                        minDate = currentDate;
                    }
                } else {
                    minDate = currentDate;
                }
                calendar.setTime(minDate);
                int minYear = calendar.get(Calendar.YEAR);
                int minMonth = calendar.get(Calendar.MONTH) + 1;
                int minDay = calendar.get(Calendar.DAY_OF_MONTH);

                calendar.setTime(mDefaultEndDate);
                int maxYear = calendar.get(Calendar.YEAR);
                int maxMonth = calendar.get(Calendar.MONTH) + 1;
                int maxDay = calendar.get(Calendar.DAY_OF_MONTH);

                DateAndTimePickerDialog.Builder builder = new DateAndTimePickerDialog
                        .Builder(mActivity)
                        .setTitle("选择结束时间")
                        .setMinYear(minYear)
                        .setMinMonth(minMonth)
                        .setMinDay(minDay)
                        .setMaxYear(maxYear)
                        .setMaxMonth(maxMonth)
                        .setMaxDay(maxDay)
                        .setOnDateSelectedListener(new DateAndTimePickerDialog.OnDateTimeSelectedListener() {
                            @Override
                            public void onDateTimeSelected(String s) {
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                                String currentDateString = sdf.format(new Date());
                                //								LogUtils.showInfoLog("currentDateString = " + currentDateString);
                                //								LogUtils.showInfoLog("selectDateString = " + s);
                                Date currentDate = DateUtil.formatDateStr(currentDateString, "yyyy-MM-dd HH:mm");
                                Date selectDate = DateUtil.formatDateStr(s, "yyyy-MM-dd HH:mm");
                                if (selectDate.before(currentDate)) {
                                    Toast.makeText(getContext(), "结束时间不能早于当前时间", Toast.LENGTH_SHORT).show();
                                } else if (selectDate.after(mDefaultEndDate)) { // 结束时间不能晚于操作者权限结束时间
                                    Toast.makeText(getContext(), "结束时间不能晚于操作者权限结束时间", Toast.LENGTH_SHORT).show();
                                } else {
                                    if (mStartDate != null) {
                                        if (!selectDate.after(mStartDate)) {
                                            Toast.makeText(mActivity, "结束时间必须晚于开始时间", Toast.LENGTH_SHORT).show();
                                        } else {
                                            mEndDate = selectDate;
                                            mTvEndTime.setText(s);
                                            mBtnDefaultEnd.setVisibility(View.VISIBLE);
                                        }
                                    } else {
                                        mEndDate = selectDate;
                                        mTvEndTime.setText(s);
                                        mBtnDefaultEnd.setVisibility(View.VISIBLE);
                                    }
                                }
                            }

                            @Override
                            public void onCancel() {

                            }
                        });
                if (mEndDate != null) {
                    calendar.setTime(mEndDate);
                    builder.setSelectYear(calendar.get(Calendar.YEAR));
                    builder.setSelectMonth(calendar.get(Calendar.MONTH) + 1);
                    builder.setSelectDay(calendar.get(Calendar.DAY_OF_MONTH));
                    builder.setSelectHour(calendar.get(Calendar.HOUR_OF_DAY));
                    builder.setSelectMin(calendar.get(Calendar.MINUTE));
                }
                DateAndTimePickerDialog timePickerDialog = builder.create();
                timePickerDialog.show();
            }
        });

        mBtnDefaultStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTvStartTime.setText(null);
                mBtnDefaultStart.setVisibility(View.INVISIBLE);
                mStartDate = null;
            }
        });

        mBtnDefaultEnd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTvEndTime.setText(null);
                mBtnDefaultEnd.setVisibility(View.INVISIBLE);
                mEndDate = null;
            }
        });

        mBtnToDistribute.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectedUserIds != null) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("businessUnitId", mBusinessUnitId);
                    map.put("selectedUserIds", mSelectedUserIds);
                    List<Long> cardAuthUkidLists = new ArrayList<>();
                    for (AuthorityDistributeItemBean itemBean : mSelectedDataList) {
                        cardAuthUkidLists.add(itemBean.userCardAuthorityUkid);
                    }
                    map.put("userCardAuthorityUkids", cardAuthUkidLists);
                    Date currentDate = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    if (mStartDate != null) {
                        map.put("validDate", sdf.format(mStartDate));
                    } else {
                        map.put("validDate", sdf.format(currentDate));
                    }
                    if (mEndDate != null) {
                        map.put("invalidDate", sdf.format(mEndDate));
                    } else {
                        map.put("invalidDate", sdf.format(mDefaultEndDate));
                    }
                    showProgressDialog();
                    NoHttpUtils.httpPost(UserCenterConstant.TEAM_BATCH_ADD_AUTHOR, map, mResponseListener, 1);
                } else {
                    Date currentDate = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Map<String, Object> map = new HashMap<>();
                    if (mStartDate != null) {
                        map.put("authStart", sdf.format(mStartDate));
                    } else {
                        map.put("authStart", sdf.format(currentDate));
                    }
                    if (mEndDate != null) {
                        map.put("authEnd", sdf.format(mEndDate));
                    } else {
                        map.put("authEnd", sdf.format(mDefaultEndDate));
                    }
                    map.put("businessId", mBusinessUnitId);
                    List<Long> cardAuthUkidList = new ArrayList<>();
                    for (AuthorityDistributeItemBean itemBean : mSelectedDataList) {
                        cardAuthUkidList.add(itemBean.userCardAuthorityUkid);
                    }
                    map.put("cardAuthUkids", cardAuthUkidList);
                    showProgressDialog();
                    NoHttpUtils.httpPost(UserCenterConstant.GET_AUTH_PROCESS_UKID, map, mResponseListener, 0);
                }

            }
        });

    }


    @Override
    public void setTitle() {
        if (peekFragment() instanceof AuthoritySetTimeFragment) {
            mActivity.setTitle("设置权限授权期");
        }
    }

    @Override
    public void requestDatas() {

    }
}
